import { defineStore } from 'pinia'
import { computed } from 'vue'

const useUserStore = defineStore('user', () => {
  const localToken = localStorage.getItem('accessToken') === 'null' ? '' : localStorage.getItem('accessToken')
  const token = ref(localToken || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')) || {})
  const setToken = (tokenKey) => {
    token.value = tokenKey
    localStorage.setItem('accessToken', token.value)
  }
  const removeToken = () => {
    localStorage.removeItem('accessToken')
    token.value = ''
  }
  const getToken = computed(() => {
    if (token.value) {
      return token.value
    } else if (localStorage.getItem('accessToken') !== 'null') {
      return localStorage.getItem('accessToken')
    } else if (sessionStorage.getItem('accessToken') !== 'null') {
      return sessionStorage.getItem('accessToken')
    }
  })
  const setUserInfo = (info) => {
    userInfo.value = {
      ...userInfo.value,
      ...info
    }
    localStorage.setItem('userInfo', JSON.stringify(info))
  }
  const removeUserInfo = () => {
    localStorage.removeItem('userInfo')
    userInfo.value = {}
  }
  const getUserInfo = computed(() => {

    console.log('%c [  ]-35', 'font-size:13px; background:pink; color:#bf2c9f;', userInfo.value)
    return Object.keys(userInfo.value).length ? userInfo.value : JSON.parse(localStorage.getItem('userInfo'))
  })

  return {
    getToken,
    setToken,
    removeToken,
    getUserInfo,
    setUserInfo,
    removeUserInfo
  }
})

export default useUserStore 